package cn.xuxiu.org.controller;

import cn.xuxiu.bacsic.util.AjaxResult;
import cn.xuxiu.bacsic.util.PageList;
import cn.xuxiu.org.domain.Department;
import cn.xuxiu.org.query.DepartmentQuery;
import cn.xuxiu.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(value = "部门API", description = "部门的crud操作")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    /**
     * 修改和添加操作
     * @param department
     * @return
     */
    @PutMapping
    @ApiOperation(value = "添加和修改操作")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if (department.getId() != null){
                departmentService.update(department);
            } else {
                departmentService.save(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统故障稍后再试！");
        }
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询")
    public Department queryById(@PathVariable("id") Long id){
        Department department = departmentService.loadById(id);
        return department;
    }

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    @ApiOperation(value = "查询全部")
    public List<Department> queryAll(){
        List<Department> departments = departmentService.loadAll();
        return departments;
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除")
    public AjaxResult removeId(@PathVariable("id") Long id){
        try {
            departmentService.del(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统故障稍后再试！");
        }
    }

    /**
     * 分页或高级查询
     * @param departmentQuery
     * @return
     */
    @PostMapping
    @ApiOperation(value = "高级查询")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryPage(departmentQuery);

    }

    @PatchMapping
    @ApiOperation(value = "根据id删除")
    public AjaxResult batchRemove(@RequestBody List<Long> ids){
        try {
            departmentService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统故障稍后再试！");
        }
    }

    @GetMapping("/tree")
    public List<Department> deptTree(){
        return departmentService.deptTree();
    }

}
